package com.googlecode.quillen.util;

import java.io.RandomAccessFile;
import java.io.File;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: greg
 * Date: Dec 17, 2008
 * Time: 1:54:46 PM
 */
public class QuillenOutputFile extends RandomAccessFile
{
    private final long size;
    private long bytesWritten = 0;
    private final Runnable onDone;

    public QuillenOutputFile(File file, long size, Runnable onDone) throws IOException
    {
        super(file, "rw");
        setLength(size);
        this.size = size;
        this.onDone = onDone;
    }

    public synchronized void write(long pos, byte[] data) throws IOException
    {
        seek(pos);
        write(data);
        bytesWritten += data.length;

        if (bytesWritten >= size)
        {
            close();

            if (onDone != null)
            {
                onDone.run();
            }
        }
    }
}
